package com.gitee.wsl.ext.number

import kotlin.math.pow

/** Easing function, based on exponent. 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out.
 * Negative values are in-out/out in.
 * Value must be between 0 and 1.
 */
fun ease(value: Float, curve: Float): Float = ease(value.toDouble(), curve.toDouble()).toFloat()

/** Easing function, based on exponent. 0 is constant, 1 is linear, 0 to 1 is ease-in, 1+ is ease out.
 * Negative values are in-out/out in.
 * Value must be between 0 and 1.
 */
fun ease(value: Double, curve: Double): Double {
    val s = when {
        value < 0 -> 0.0
        value > 1.0 -> 1.0
        else -> value
    }

    return when {
        curve > 0.0 -> {
            if (curve < 1.0) {
                val a = 1.0 - s
                1.0 - a.pow(1.0 / curve)
            } else {
                s.pow(curve)
            }
        }

        curve < 0.0 -> {
            if (value < 0.5) {
                val a = s * 2.0
                a.pow(-curve) * 0.5
            } else {
                val a = 1.0 - (s - 0.5) * 2.0
                (1.0 - a.pow(-curve)) * 0.5 + 0.5
            }
        }

        else -> 0.0
    }
}